package.path = package.path .. ";lualib/?.lua"
package.cpath = package.cpath .. ";luaclib/?.so;"

require "core.Util"

local arg = arg
local force = table.contain(arg, "-f") or table.contain(arg, "--force")

local lfs = require "lfs"
local pb = require "pb"
local Protoc = require "Protoc"

local function scan_proto(path, func)
    for file in lfs.dir(path) do
        if file ~= "." and file ~= ".." and file:sub(1, 1) ~= "." then
            local f = path .. '/' .. file
            local attr = lfs.attributes(f)
            assert(type(attr) == "table")
            if attr.mode == "directory" then
                scan_proto(f, func)
            else
                if file:sub(-6) == ".proto" then
                    func(path, file)
                end
            end
        end
    end
end

local function normailze(mod)
    return mod:gsub("^%l", string.upper)
end

-- 获取 ../proto 的绝对路径
local protoRoot = "../proto"
local targetRoot = "./modules"
scan_proto(protoRoot, function(dir, file)
    local relativeDir = dir:sub(protoRoot:len() + 2)
    local protoFile = dir .. '/' .. file
    local relativePath = protoFile:sub(protoRoot:len() + 2)
    local target = targetRoot .. "/" .. relativeDir .. "/" .. normailze(file:sub(1, -6)) .. "pb"
    local attrs = lfs.attributes(target)
    if attrs then
        if not force and attrs.modification > lfs.attributes(protoFile).modification then
            print("文件未更新，跳过文件: " .. protoFile)
            return
        end
    end

    local pc = Protoc.new()
    -- pc.include_imports = true
    pc.proto3_optional = true
    pc:addpath(protoRoot)
    local data = pc:compilefile(protoFile)
    local file, err = io.open(target, "wb")
    assert(file, "文件创建失败: " .. tostring(err))
    print(string.format("%s -> %s", protoFile, target))
    file:write(data)
end)
